<!-- eslint-disable no-sequences -->
<template>
  <div class='container'>
    <div class="card">
      <!-- 面试技巧 -->
      <div class="elRow">
      <el-row>
      <el-col :span="18">
        <div class="grid-content bg-purple">
         <el-form class="FromBox">
          <el-form-item label="关键词" class="elFrom">
            <el-input v-model="pageform.keyword" size="small"  placeholder="根据文章标题搜索"></el-input>
          </el-form-item>
          <el-form-item label="状态" class="elFrom">
            <el-select v-model="pageform.state" placeholder="请选择">
            <el-option  v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="clearClick">清除</el-button>
            <el-button type="primary" size="small" @click="changeValue">搜索</el-button>
          </el-form-item>
         </el-form>
        </div>
        </el-col>
      <el-col :span="6" style="text-align: right;">
        <div class="grid-content bg-purple-light">
        <el-button type="success" size="small" icon="el-icon-edit" class="elButton" @click="addClick">新增文章</el-button>
        </div>
        </el-col>
      </el-row>
    </div>
    <!-- 数据一共4条 -->
    <div class="elAlert">
      <template >
        <el-alert :title="`数据一共${total}条`" type="info" show-icon :closable="false"></el-alert>
      </template>
    </div>
    <!-- 学科表格 -->
    <div>
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#fafafa' }" cellspacing="1"  cellpadding="5"  class="el-table__header">
    <el-table-column type="index"  label="序号" width="90"  align="center">
    </el-table-column>
    <el-table-column prop="title" label="文章标题" width="350" >
      <template v-slot="{row}">
        {{  row.title  }}<i class="el-icon-film" v-if="row.videoURL" ></i>
      </template>
       </el-table-column>
    <el-table-column prop="visits" label="阅读数"  width="120"  align="center"></el-table-column>
    <el-table-column prop="username" label="录入人" width="110"  align="center"> </el-table-column>
    <el-table-column prop="addDate" label="录入时间" width="180"  align="center">
      <template v-slot="{row}">
        <span>{{ StringDateToDate(row.createTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="state" label="状态" width="100"  align="center">
      <template v-slot="{row}">
        <span v-if="row.state===1">已启动</span>
        <span v-if="row.state===0">已禁用</span>
      </template>
       </el-table-column>
    <el-table-column  label="操作" width="240"  align="center">
    <template v-slot="{row}" >
     <el-button  type="text" size="small" @click="editClick('preview',row.id)"> 预览 </el-button>
     <el-button  type="text" size="small" @click="Disabled(row)"> {{ row.state===1?"启用":'禁用' }} </el-button>
     <el-button  type="text" size="small"  :disabled="row.state===1" @click="editClick('edit',row.id)"> 修改 </el-button>
     <el-button  type="text" size="small" :disabled="row.state===1"  @click="deleteClick(row.id)"> 删除 </el-button>
    </template>
    </el-table-column>
  </el-table>
    </div>
    <!-- 分页 size-change 每页条数发生改变 current-change当前页改变 current-page当前页数 page-size每页显示条目个数-->
    <el-row>
      <el-col :span="24" style="text-align: right;" class="Pagination">
    <div class="grid-content bg-purple-dark">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pageform.page" :page-sizes="[5, 10, 20, 50]"  background :total="total"
      :page-size="pageform.pagesize" layout="prev, pager, next, sizes, jumper" > </el-pagination>
    </div>
  </el-col>
  </el-row>
  <!-- 模态框 -->
  <el-dialog  v-if="drawerType ==='preview'" title="预览文章" :visible.sync="dialogFormVisible" width="820px">
    <h2>{{ form.title }}</h2>
    <p>{{ StringDateToDate(form.createTime) }}  超级管理员  <i class="el-icon-view"></i> {{ form.visits}}</p>
    <div class="dialogBox" v-html="form.articleBody">   </div>
  </el-dialog>
  <el-dialog v-else :title="edit?'编辑文章':'新增文章'" :visible.sync="dialogFormVisible" width="820px">
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
    <el-form-item label="文章标题" prop="title" >
      <el-input v-model="form.title" autocomplete="off" placeholder="请输入文章标题" ></el-input>
    </el-form-item>
    <el-form-item label="文章内容" prop="articleBody">
    <vue-editor v-model="form.articleBody" />
  </el-form-item>
  <el-form-item label="视频地址" prop="videoURL" >
      <el-input v-model="form.videoURL" autocomplete="off" placeholder="请输入视频地址" ></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="resetForm">取 消</el-button>
    <el-button type="primary" @click="submitForm">确 定</el-button>
  </div>
</el-dialog>
    </div>
    </div>
</template>

<script>
import { list, changeState, remove, add, detail, update } from '@/api/hmmm/articles'
// import dayjs from 'dayjs'
import { VueEditor } from 'vue2-editor'
export default {
  components: {
    VueEditor
  },
  data () {
    return {
      options: [{
        value: '1',
        label: '启动'
      }, {
        value: '0',
        label: '禁用'
      }],
      state: '0',
      dialogFormVisible: false, // 模态框默认关闭
      edit: false, // 来控制点击的是编辑还是新增 编辑为true 新增为false
      drawerType: '', // 来控制预览文章和编辑新增文章 模态框的样式
      total: 0, // 总数
      pageform: {
        page: 1, // 当前页码
        pagesize: 10 // 每页显示多少条数据
      },
      tableData: [], // 表单内容
      form: {
        id: '', // id
        title: '', // 文章标题
        articleBody: '', // 文章正文
        videoURL: '', // 视频地址
        createTime: '', // 时间
        visits: '', // 阅读量
        username: '' // 录入人
      },
      // 非空正则校验
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 调用学科列表请求
    this.subjectsList(this.pageform)
  },
  methods: {
    // 发送axios请求 进行页面渲染
    async subjectsList (pageform) {
      try {
        const { data } = await list(pageform)
        this.tableData = data.items
        this.total = data.counts
      } catch (error) {
        console.log(error)
      }
    },
    // 禁用按钮
    async Disabled (row) {
      this.form.id = row.id
      console.log(this.form.state)
      try {
        // 发送请求
        const res = await changeState({
          id: this.form.id,
          state: row.state === 0 ? 1 : 0
        })
        console.log(res)
        // 调用学科列表请求
        this.subjectsList()
        // 提示框
        this.$message('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 字符串时间转正常格式
    StringDateToDate (str) {
      // 输入的字符串
      var input = str
      // 将输入字符串解析为日期对象
      var date = new Date(input)
      // 使用Date对象的方法将其格式化为所需的字符串格式
      var output = date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '')
      // console.log(output) // 输出：2023-04-18 08:53:38
      return output
    },
    // 每页条数发生改变
    handleSizeChange (newSize) {
      console.log(newSize)
      // 将监听的每页显示多少条数据赋值给当前
      this.pageform.pagesize = newSize
      // 重新发请求
      this.subjectsList(this.pageform)
    },
    //  当前页改变
    handleCurrentChange (newPage) {
      console.log(newPage)
      // 将监听接受到的页码值的数据 newPage 赋值给 pagenum
      this.pageform.page = newPage
      // 重新发请求
      this.subjectsList(this.pageform)
    },
    // 点击搜索框
    async changeValue () {
      this.pageform.page = 1
      this.pageform.pagesize = 5
      console.log(this.pageform)
      await this.subjectsList(this.pageform)
    },
    // 点击清除按钮
    clearClick () {
      // eslint-disable-next-line no-unused-expressions, no-sequences
      this.pageform.keyword = '',
      this.pageform.state = ''
    },
    // 预览文章/编辑学科
    async editClick (item, id) {
      this.dialogFormVisible = true
      this.drawerType = item
      this.edit = true
      this.form.id = id
      try {
        // 发送编辑学科的请求 进行数据回显功能
        const res = await detail({ id })
        console.log(res)
        console.log(this.form)
        this.form = res.data
        console.log(this.form)
      } catch (error) {
        console.log(error)
      }
    },
    // 新增文章
    addClick () {
      this.dialogFormVisible = true
      this.edit = false
    },
    // 删除文章
    deleteClick (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$message({
          // 发送删除学科的请求
          type: 'success',
          message: '删除成功!'
        })
        try {
          await remove({ id })
          // 调用学科列表请求
          this.subjectsList()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 点击模态框确定按钮
    submitForm () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 条件判断 若为true 则发送修改的请求 若为fales 则发送新增的请求
          if (this.edit) {
            console.log(this.edit)
            // 发送修改的请求
            const obj = {
              id: this.form.id,
              title: this.form.title,
              articleBody: this.form.articleBody,
              videoURL: this.form.videoURL
            }
            try {
              const res = await update(obj)
              console.log(res)
              this.$message('编辑成功')
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log(this.edit)
            try {
              // 发送新增的请求
              const res = await add({
                title: this.form.title,
                articleBody: this.form.articleBody,
                videoURL: this.form.videoURL
              })
              console.log(res)
              this.$message('新增成功')
            } catch (error) {
              console.log(error)
            }
          }
          // 调用学科列表请求
          this.subjectsList()
          this.dialogFormVisible = false
          this.$refs.ruleForm.resetFields()
        } else {
          this.$message('请输入正确信息')
          return false
        }
      })
    },
    // 点击模态框取消按钮
    resetForm () {
      this.dialogFormVisible = false
      this.$refs.ruleForm.resetFields()
      this.$message('已取消')
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  // padding: 0 10px;
  margin: 5px 0;
  width: 100%;
  height: 100%;
  background: #ebedf0;
}
.card {
  width: 100%;
  height: 100%;
  padding: 20px 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  transition: .3s;
  border-radius: 4px;
  overflow: hidden;
}
.FromBox {
  box-sizing: inherit;
  display: flex;
  color: #303133;
}
.elFrom {
  margin-left: 20px;
  display: flex;
  margin-right: 10px;
}
.elButton {
  text-align: right;
  margin-right: 10px;
}
.el-icon-film {
  margin-left: 10px;
  color: #00f;
}
.elAlert {
  margin-bottom: 20px;
}
.el-table .btn-next .warning-row {
    background: oldlace;
  }
.el-table .success-row {
    background: #f0f9eb;
  }
.el-table__header {
  font-size: 14px;
    color: #606266
}
::v-deep  .el-table__header  .el-table__cell .el-button--small {
  font-size: 14px;
}
.Pagination .grid-content {
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
 ::v-deep .el-pagination  .el-pagination__jump {
  margin-left: 3px;
  z-index: 9999;
}
.dialog-footer {
  display: flex;
  justify-content: right;
}
.dialogBox {
  width: 100%;
  height: 100%;
  padding: 10px 10px;
  background: #f5f5f5;
  border-top: 1px dashed #cccccc;
}
::v-deep .el-dialog__body {
  padding: 15px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
</style>
